package com.mvp.shq.washer.ui.shop.order.refund;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.OrderListAdapter;
import com.mvp.shq.washer.adapter.OrderPayListAdapter;
import com.mvp.shq.washer.adapter.TypeChoseAdapter;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.entity.ShopSortType;
import com.mvp.shq.washer.entity.shop.ShopSpec;
import com.mvp.shq.washer.entity.shop.result.OrderDataListResult;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.ImageUtil;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.view.widget.PayTypePopupWindow;
import com.mvp.shq.washer.view.widget.RefundTypePopupWindow;
import com.mvp.shq.washer.view.widget.SpecPopupWindow;
import com.mvp.shq.washer.view.widget.TypePopupWindow;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by westing on 2017/10/12.
 * 退款界面
 */
@RuntimePermissions
public class RefundActivity extends BaseActivity<Presenter, Model> implements RefundConstract.View {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.lin_type)
    LinearLayout linType;
    @BindView(R.id.tv_recouse)
    TextView tvRecouse;
    @BindView(R.id.lin_recouse)
    LinearLayout linRecouse;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_ji)
    TextView tvJi;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.et_message)
    EditText etMessage;
    @BindView(R.id.img1)
    ImageView img1;
    @BindView(R.id.bnt_delete1)
    Button bntDelete1;
    @BindView(R.id.lin_img1)
    FrameLayout linImg1;
    @BindView(R.id.img2)
    ImageView img2;
    @BindView(R.id.bnt_delete2)
    Button bntDelete2;
    @BindView(R.id.lin_img2)
    FrameLayout linImg2;
    @BindView(R.id.img3)
    ImageView img3;
    @BindView(R.id.bnt_delete3)
    Button bntDelete3;
    @BindView(R.id.lin_img3)
    FrameLayout linImg3;
    @BindView(R.id.imgadd)
    ImageView imgadd;
    @BindView(R.id.bnt_take)
    TextView bntTake;
    private TypePopupWindow popupWindow;
    private RefundTypePopupWindow refundTypePopupWindow;
    List<ShopSortType> mTypeList;
    private String orderId;
    private double cashPrice,integoryPrice,totalPrice;
    private List<File> imgFiles;
    private FrameLayout[] imgFrameLayout;
    private ImageView[] imgs;
    private ImageUtil imageUtil;
    private OrderPayListAdapter listadapter;
    private OrderDataListResult orderDataListResult;
    private int compressNum = 0;
    private List<RequestBody> photos;
    @Override
    public int getLayoutId() {
        return R.layout.activity_refund;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(context, R.color.money), 9);
        title.setText("申请退款");
        RxBus.get().send(EventCode.SHOP_REFUND_SEND_ORDERINFO);
        imgFiles = new ArrayList<>();
        imgFrameLayout = new FrameLayout[]{linImg1,linImg2,linImg3};
        imgs = new ImageView[]{img1,img2,img3};
        showImgs();
        tvRecouse.setText("不喜欢/效果差");
        imageUtil = new ImageUtil(context);
        initDate();
    }

    @Subscribe(code = EventCode.SHOP_REFUND_GET_ORDERINFO)
    public void initOrderInfo(OrderDataListResult result){
        orderDataListResult = result;
        listadapter = new OrderPayListAdapter(context,orderDataListResult.getEcOrderDetailList());
        recyclerview.setLayoutManager(new LinearLayoutManager(context));
        RecyclerViewDivider divider = new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL, 10, ContextCompat.getColor(context, R.color.white));
        recyclerview.addItemDecoration(divider);
        recyclerview.setAdapter(listadapter);
        orderId = result.getId();
        cashPrice = result.getCashPrice();
        integoryPrice = result.getIntegralPrice();
        totalPrice = result.getCashPrice();
        tvMoney.setText("￥"+cashPrice);
        tvJi.setText(""+integoryPrice);
        tvAccount.setText("最多￥"+cashPrice+"、积分"+integoryPrice+"，含配送费￥0");
    }

    private void initDate() {
        mTypeList=new ArrayList<>();
        mTypeList.add(new ShopSortType("未收到货",false));
        mTypeList.add(new ShopSortType("已收到货",true));
    }

    @OnClick({R.id.back,R.id.lin_type, R.id.lin_recouse, R.id.bnt_delete1, R.id.bnt_delete2, R.id.bnt_delete3, R.id.imgadd, R.id.bnt_take})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.lin_type:
                //货物状态
                showPopType();
                break;
            case R.id.lin_recouse:
                //退货原因
                showPopRefundType();
                break;
            case R.id.bnt_delete1:
                //删除第一张
                imgFiles.remove(0);
                showImgs();
                break;
            case R.id.bnt_delete2:
                //删除第二张
                imgFiles.remove(1);
                showImgs();
                break;
            case R.id.bnt_delete3:
                //删除第三张
                imgFiles.remove(2);
                showImgs();
                break;
            case R.id.imgadd:
                //添加图片
                if (imgFiles.size() >= 3){
                    T.show("最多上传三张图片");
                    return;
                }
                RefundActivityPermissionsDispatcher.toChooseImgWithCheck(this);
                break;
            case R.id.bnt_take:
                //提交
                showLoadingDialog(true);
                compressNum = 0;
                compressImg(imgFiles.get(compressNum));
                break;
        }
    }
    /**
     *  显示货物状态对话框
     */
    private void showPopType(){
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
        if (popupWindow == null){
            popupWindow = new TypePopupWindow(context, this, new TypePopupWindow.OnCheckListener() {
                @Override
                public void onCheck(int position) {
                    String name=mTypeList.get(position).getName();
                    tvType.setText(""+name);
                }
            });
        }
        popupWindow.showAtLocation(back, Gravity.BOTTOM,0,0);
    }
    /**
     *  显示退款原因选择对话框
     */
    private void showPopRefundType(){
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
        if (refundTypePopupWindow == null){
            refundTypePopupWindow = new RefundTypePopupWindow(context, this, new RefundTypePopupWindow.OnCheckListener() {
                @Override
                public void onCheck(String content) {
                    tvRecouse.setText(content);
                }
            });
        }
        refundTypePopupWindow.showAtLocation(back, Gravity.BOTTOM,0,0);
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    public void toChooseImg() {
        int MAX = 3;
        int num = 1;
        num = MAX - imgFiles.size();
        PhotoPicker.builder()
                .setPhotoCount(num)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE);
    }
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(context)
                .setMessage("是否开启相机权限")
                .setPositiveButton("同意", (dialog, button) -> request.proceed())
                .setNegativeButton("拒绝", (dialog, button) -> request.cancel())
                .show();
        Toast.makeText(context, "showRationaleForCamera", Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        Toast.makeText(context, "拒绝相机权限将无法上传图片", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        Toast.makeText(context, "相关权限无法使用", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        RefundActivityPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.d("resultCode:"+resultCode+"------------requestCode:"+requestCode);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) { //RESULT_OK = -1
            if (data != null){
                List<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (photos == null || photos.size() <= 0){
                    return;
                }
                for (int i=0;i<photos.size();i++){
                    File file = new File(photos.get(i));
                    imgFiles.add(file);
                }
                showImgs();
//                showLoadingDialog(true);
//                compressImg(file);
            }
        }
    }

    private void showImgs(){
        for (int i=0;i<imgFrameLayout.length;i++){
            imgFrameLayout[i].setVisibility(View.GONE);
        }
        for (int i=0;i<imgFiles.size();i++){
            imgFrameLayout[i].setVisibility(View.VISIBLE);
            Uri uri = Uri.fromFile(imgFiles.get(i));
            imageUtil.loadLocalImage(uri,imgs[i]);
        }
    }

    /**
     * 图片压缩
     * @param file
     */
    private void compressImg(File file){
        Luban.with(this)
                .load(file)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
                        if (photos == null){
                            photos = new ArrayList<RequestBody>();
                        }
                        photos.add(requestBody);
                        if (compressNum == imgFiles.size() - 1){
                            String reasonStr = tvRecouse.getText().toString() + "-" + etMessage.getText().toString();
                            Map<String,RequestBody> maps = new HashMap<String, RequestBody>();
                            Logger.d("图片图片:"+photos.size());
                            for (int i=0;i<photos.size();i++){
                                maps.put("photos\";filename=\""+i+"+image.png",photos.get(i));
                            }
                            presenter.submitRefund(orderId,tvType.getText().toString(),reasonStr,maps);
                        }else {
                            Logger.d("压缩的图片:"+compressNum);
                            compressNum ++;
                            compressImg(imgFiles.get(compressNum));
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoadingDialog();
                    }
                }).launch();
    }

    @Override
    public void submitS() {
        T.show("提交成功");
        finish();
    }
}
